package server.command.client;

import app_kvServer.KVServer;
import common.messages.KVMessage.StatusType;
import utils.CommonUtil;
import utils.IKeyValueStorage;

public class CommandGet implements ICommand {
	private IKeyValueStorage storage;
	private String key;
	private KVServer server;
	
	public CommandGet(KVServer server, IKeyValueStorage storage, String key) {
		this.key = key;
		this.storage = storage;
		this.server = server;
	}
	
	@Override
	public String execute() {
		String keyHash = CommonUtil.hashString(key);
		if (KVServer.isInRange(keyHash, server.getRangeStart(), server.getRangeEnd())) {
			if (!storage.containsKey(keyHash) ) {
				return ClientInputHandler.composeClientResponse(StatusType.GET_ERROR, "no value for key "+key, "");
			}
			String value = (String) storage.get(keyHash);
			return ClientInputHandler.composeClientResponse(StatusType.GET_SUCCESS, value, "");
		}
		else {
			/** TODO what if the metadata is out of date? **/
			return ClientInputHandler.composeClientResponse(StatusType.SERVER_NOT_RESPONSIBLE, key, "");
		}
	}
}
